/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 */

import { Module } from '@ohos/hvigor';

import { CommonConst } from '../../const/common-const.js';
import { LegacyProjectModelImpl } from '../../model/project/legacy-project-model-impl.js';
import { ApiType } from '../../project/data/hap-extra-info.js';
import { OhosLogger } from '../../utils/log/ohos-logger.js';
import { AbstractModulePlugin } from '../common/abstract-module-plugin.js';
import { OhosPluginId } from '../common/ohos-plugin-id.js';
import { LegacyAppPlugin } from '../legacy/legacy-app-plugin.js';
import { LegacyHapPlugin } from '../legacy/legacy-hap-plugin.js';
import { LegacyHarPlugin } from '../legacy/legacy-har-plugin.js';

import { CorePluginBuilder } from './core-plugin-builder.js';

export class LegacyPluginBuilder extends CorePluginBuilder {
  private _log: OhosLogger = OhosLogger.getLogger(LegacyPluginBuilder.name);

  constructor(module: Module) {
    super(module);
  }

  setUpModulePlugin(plugin: AbstractModulePlugin): void {
    plugin.doModuleInspection();
    plugin.initModuleTaskService(true);
    plugin.initBuildOptionMap(this.module.getBuildProfilePath());
    plugin.initTargetDepends();
    plugin.initModuleCommonTasks();
    plugin.initModuleCommonTasksForDiffApiType(true);
  }

  createFaHapPlugin(): LegacyHapPlugin {
    return this.initPluginParam(new LegacyHapPlugin(this.module), true) as LegacyHapPlugin;
  }

  createFaHarPlugin(): LegacyHarPlugin {
    return this.initPluginParam(new LegacyHarPlugin(this.module), false) as LegacyHarPlugin;
  }

  initPluginParam(plugin: AbstractModulePlugin, isHapModule: boolean): AbstractModulePlugin {
    const projectModel = this.createProjectModel();
    const moduleModel = this.createModuleModel(projectModel, isHapModule);

    return plugin.withProjectModel(projectModel).withModuleModel(moduleModel).withPluginApiType(ApiType.FA).withRuntimeConfigFileName(CommonConst.CONFIG_JSON);
  }

  private createProjectModel(): LegacyProjectModelImpl {
    const project = this.module.getProject();
    const legacyAppPlugin = project.getPluginById(OhosPluginId.OHOS_APP_PLUGIN) as LegacyAppPlugin;
    if (!legacyAppPlugin) {
      this._log.printErrorExit(
        'FA_NO_SYSTEM_PLUGIN',
        [project.getBuildFilePath()]
      );
    }
    return legacyAppPlugin.getProjectModel() as LegacyProjectModelImpl;
  }
}
